package com.yzsj.socket.init;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yzsj.socket.business.domain.ElectricEnergyPO;
import com.yzsj.socket.business.domain.TempSituationPO;
import com.yzsj.socket.business.domain.vo.TagValueVO;
import com.yzsj.socket.business.service.ElectricEnergyService;
import com.yzsj.socket.business.service.SceneviewService;
import com.yzsj.socket.business.service.TagValueService;
import com.yzsj.socket.business.service.TempSituationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CSSTask {

    @Value("${ucweb.url}")
    private String ucwebUrl;

    @Autowired
    private ElectricEnergyService energyService;

    @Autowired
    private TempSituationService situationService;

    @Autowired
    private TagValueService tagValueService;

    @Autowired
    private SceneviewService sceneviewService;

    @Autowired
    private StartPubSub startPubSub;

    private Integer instanceAlarmCount = 1;

    public static  Map<String,TagValueVO> mapObj = new HashMap<>();

    @Scheduled(cron="0/5 * *  * * ? ")
    public void getElectricEnergyValue() {
        List<ElectricEnergyPO> newList = Lists.newArrayList();
        try {
            String result = "";
            String tmpUrl = ucwebUrl+"tag/value/list";
            URL url = new URL(tmpUrl);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            InputStreamReader ir = new InputStreamReader(is, "UTF-8");
            BufferedReader in = new BufferedReader(ir);
            String line = null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            in.close();
            if (result != "" && !result.equals("[]")) {
                List<ElectricEnergyPO> list = energyService.findAll();
                JSONArray ja = JSONArray.parseArray(result);
                if (ja != null && ja.size() > 0) {
                    for (int i = 0; i < ja.size(); i++) {
                        JSONObject jo = (JSONObject) ja.get(i);
                        String tid = jo.get("tid").toString();
                        String val = jo.get("val").toString();
                        if(tid.indexOf("46")>0 || tid.indexOf("96")>0) {
                            for(ElectricEnergyPO ee : list){
                                if(ee.getTagid().equals(tid)) {
                                    if(!ee.getTagvalue().equals(val)) {
                                        ee.setTagvalue(val);
                                        newList.add(ee);
                                    }
                                }
                            }
                        }
                    }

                    if(newList!=null && newList.size()>0){
                        energyService.saveList(newList);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron="0/5 * *  * * ? ")
    public void getTempValue() {
        List<TempSituationPO> newList = Lists.newArrayList();
        try {
            String result = "";
            String tmpUrl = ucwebUrl+"tag/value/list";
            URL url = new URL(tmpUrl);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            InputStreamReader ir = new InputStreamReader(is, "UTF-8");
            BufferedReader in = new BufferedReader(ir);
            String line = null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            in.close();
            if (result != "" && !result.equals("[]")) {
                List<TempSituationPO> list = situationService.findAll();
                JSONArray ja = JSONArray.parseArray(result);
                if (ja != null && ja.size() > 0) {
                    for (int i = 0; i < ja.size(); i++) {
                        JSONObject jo = (JSONObject) ja.get(i);
                        String tid = jo.get("tid").toString();
                        String val = jo.get("val").toString();
                        if(Integer.parseInt(tid)>59 && Integer.parseInt(tid)<109) {
                            for(TempSituationPO ts : list){
                                if(ts.getTagid().toString().equals(tid)) {
                                    if(!ts.getTagvalue().equals(val)) {
                                        ts.setTagvalue(val);
                                        Integer tempLevel = getTempLevel(val);
                                        ts.setTempLevel(tempLevel);
                                        newList.add(ts);
                                    }
                                }
                            }
                        }
                    }

                    if(newList!=null && newList.size()>0){
                        situationService.saveList(newList);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron="*/10 * * * * ?")
    public void updateAlarm(){
        try{
            String result = "";
            String tmpUrl = ucwebUrl + "alarm/active/list";
            URL url = new URL(tmpUrl);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            InputStreamReader ir = new InputStreamReader(is, "UTF-8");
            BufferedReader in = new BufferedReader(ir);
            String line = null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            in.close();
            List<String> tagids = Lists.newArrayList();
            //将报警信息存到变量表
            if (result != "" && !result.equals("[]")) {
                JSONArray ja = JSONArray.parseArray(result);
                if (ja != null && ja.size() > 0) {
                    List<TagValueVO> taginfoLists = Lists.newArrayList();
                    for (int i = 0; i < ja.size(); i++) {
                        JSONObject jo = (JSONObject) ja.get(i);
                        String tid = jo.get("TagID").toString();
                        String val = jo.get("AlmValue").toString();
                        String alarmPriority = jo.get("AlmPriority").toString();//报警优先级
                        if (val.indexOf(".")>=0) {
                            val += "000";
                            val = val.substring(0,val.indexOf(".")+3);
                        }
                        if(val.equals("1.00")){
                            val = "1";
                        }
                        if(val.equals("0.00")){
                            val = "0";
                        }
                        String webTime = jo.get("AlmTime").toString();
                        TagValueVO taginfo = mapObj.get(tid);
                        if (taginfo != null) {
                            taginfo.setIsalarming(1);
                            taginfo.setAlarmpro(Integer.parseInt(alarmPriority));
                            if(taginfo.getTagtype()!=null && taginfo.getTagtype()==1){
                                val = getKpiUnit(taginfo.getTagvalue(), val);
                            }
                            taginfo.setValue(val);
                            taginfo.setWarningtime(webTime);
                            taginfoLists.add(taginfo);
                            tagids.add(taginfo.getTagid());
                        }
                    }
                    if(taginfoLists.size()>0){
                        tagValueService.saveList(taginfoLists);
                    }
                }
            }
            //System.out.println(tagids);
            //根据变量id修改设备表的报警状态
            if(tagids.size()>0){
                //报警的设备
                sceneviewService.updateByTagId(tagids);
                //不报警的设备
                sceneviewService.updateNotByTagId(tagids);
                //不报警的变量
                tagValueService.updateNotByTagId(tagids);
            }else{
                sceneviewService.updateAllisNotAlarm();
                tagValueService.updateAll();
            }
            startPubSub.initRedis();
            while (StartPubSub.refreshing) {

            }
//	        System.out.println("初始化完成");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 温度的值进行分段：0-15℃--1，15-20℃--2，20-25℃--3，25-30℃--4，>30℃--5
     * @param val 温度值
     * @return
     */
    private static Integer getTempLevel(String val) {
        int tempLevel = 1;
        Double tempVal = 0.0;
        if(val!=null && !val.equals("")) {
            tempVal = Double.parseDouble(val);
        }
        if(tempVal>=0 && tempVal<15) {
            tempLevel = 1;
        } else if(tempVal>=15 && tempVal<20) {
            tempLevel = 2;
        } else if (tempVal>=20 && tempVal<25){
            tempLevel = 3;
        } else if (tempVal>=25 && tempVal<30){
            tempLevel = 4;
        } else {
            tempLevel = 5;
        }
        return tempLevel;
    }

    private static String getKpiUnit(String valExplain, String tagVal) {
        if (tagVal == null || tagVal.isEmpty()) {
            return "";
        }
        if(valExplain==null || valExplain==""){
            return tagVal;
        }
        String[] valEs = valExplain.split(",");
        if(valEs.length>0){
            if (tagVal.equals("0")) {
                return valEs[0];
            }else{
                return valEs[1];
            }
        }else{
            return tagVal;
        }
    }
}
